package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 42
 * @date 2025/4/1
 * @Description
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShopCartMapper shopCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单接口
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public Result<OrderSubmitVO> submit(OrdersSubmitDTO ordersSubmitDTO) {

        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);

        //查询地址铺的信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        //异常情况
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());

        //查询购物车的数据
        List<ShoppingCart> shoppingCartList = shopCartMapper.list(BaseContext.getCurrentId());
        if(shoppingCartList == null || shoppingCartList.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向数据库插入订单数据,记得设置主键返回
        orderMapper.insert(orders);

        List<OrderDetail> list = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            list.add(orderDetail);
        }
        //批量插入订单细节数据
        orderDetailMapper.insertBatch(list);

        //删除商品购物车的信息
        shopCartMapper.deleteByUserId(BaseContext.getCurrentId());

        //封装返回数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return Result.success(orderSubmitVO);
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

/*
        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
*/

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改
        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单

        //发现没有将支付时间 check_out属性赋值，所以在这里更新
        LocalDateTime check_out_time = LocalDateTime.now();

        //获取订单号码
        String orderNumber = ordersPaymentDTO.getOrderNumber();

        log.info("调用updateStatus，用于替换微信支付更新数据库状态的问题");
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, orderNumber);

        Orders orders = orderMapper.getByNumberAndUserId(orderNumber, userId);
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orderNumber);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        return vo;

    }

    /**
     * 支付成功，修改订单状态(未调用)
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }

    /**
     * 订单分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public Result<PageResult> page(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        //分页查询
        List<OrdersVO> info = orderMapper.list(ordersPageQueryDTO);

        //组装菜品字符串
        for (OrdersVO ordersVo : info) {
            StringBuilder string = new StringBuilder();
            Long orderId = ordersVo.getId();
            //取出每个订单的详细信息
            List<OrderDetail> orderDetailList = orderDetailMapper.list(orderId);
            //再次循环拿到要拼接的信息
            for (OrderDetail detail : orderDetailList) {
                string.append(detail.getName()+"*"+detail.getNumber()+";");
            }
            //保存到原视图
            ordersVo.setOrderDishes(string.toString());
        }

        PageInfo<OrdersVO> pageInfo = new PageInfo<>(info);

        PageResult pageResult = new PageResult();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setRecords(pageInfo.getList());

        return Result.success(pageResult);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public Result<OrderStatisticsVO> statistics() {

        OrderStatisticsVO result = new OrderStatisticsVO();
        result.setConfirmed(orderMapper.getOrderStatusNum(Orders.CONFIRMED));
        result.setDeliveryInProgress(orderMapper.getOrderStatusNum(Orders.DELIVERY_IN_PROGRESS));
        result.setToBeConfirmed(orderMapper.getOrderStatusNum(Orders.TO_BE_CONFIRMED));


        return Result.success(result);
    }

    /**
     * 根据id查询订单详情
     * @param id
     * @return
     */
    @Override
    public Result<OrderVO> detail(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders order = orderMapper.getById(id);
        BeanUtils.copyProperties(order,orderVO);

        List<OrderDetail> orderDetailList = orderDetailMapper.list(id);
        StringBuilder string = new StringBuilder();
        for (OrderDetail orderDetail : orderDetailList) {
            string.append(orderDetail.getName()+"*"+orderDetail.getNumber()+";");

        }
        orderVO.setOrderDishes(string.toString());
        orderVO.setOrderDetailList(orderDetailList);

        return Result.success(orderVO);
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     * @return
     */
    @Override
    public Result confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
        return Result.success();
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     * @return
     */
    @Override
    public Result reject(OrdersRejectionDTO ordersRejectionDTO) {
        //拒绝订单只有待接单的时候才可以拒绝订单
        Orders order = orderMapper.getById(ordersRejectionDTO.getId());
        if(order == null || !order.getStatus().equals(Orders.REFUND) ){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //拒绝订单都是付款则需要申请退款
        Integer payStatus = order.getPayStatus();
        if(payStatus == Orders.PAID){
            log.info("调用微信支付接口,传递订单号申请退款");
//            try {
//                weChatPayUtil.refund(order.getNumber(),order.getNumber(),order.getAmount(),order.getAmount());
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
        }
        //修改数据库状态（orders表的status专题，改为6，添加rejection_reason和cancel_reason）
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .payStatus(Orders.REFUND)
                .status(Orders.CANCELLED)
                .cancelReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        return Result.success();
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     * @return
     */
    @Override
    public Result cancel(OrdersCancelDTO ordersCancelDTO) {
        //待付款的取消不需要退款，待派送、派送中、已完成的都需要退款
        //可以根据支付状态来判断

        //1.查询订单状态
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        if(orders.getPayStatus().equals(Orders.PAID)){
            //为已支付的进行退款,调用微信接口
            log.info("申请退款:{}",orders.getAmount());
        }
        //2.修改订单状态
        Orders build = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .payStatus(Orders.REFUND).build();
        orderMapper.update(build);

        return Result.success();
    }

    /**
     * 派送订单
     * @param id
     * @return
     */
    @Override
    public Result delivery(Long id) {
        //查询订单数据
        Orders orders = orderMapper.getById(id);
        //只有已接单的订单才可派送
        if(orders==null || !orders.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders build = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(build);
        return Result.success();
    }

    /**
     * 完成订单
     * @param id
     * @return
     */
    @Override
    public Result complete(Long id) {

        Orders orders = orderMapper.getById(id);

        if(orders==null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        }
        Orders build = Orders.builder()
                .id(id)
                .deliveryTime(LocalDateTime.now())
                .status(Orders.COMPLETED)
                .build();
        orderMapper.update(build);
        return Result.success();
    }

    /**
     * 用户分页查询订单
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public Result<PageResult> pageHistory(int page, int pageSize, Integer status) {
        PageHelper.startPage(page,pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setPage(page);
        ordersPageQueryDTO.setPageSize(pageSize);
        ordersPageQueryDTO.setStatus(status);
        List<OrderVO> list = orderMapper.getOrderList(ordersPageQueryDTO);

        if(list == null || list.size() == 0){
            PageResult pageResult = new PageResult();
            pageResult.setTotal(0);
            pageResult.setRecords(new ArrayList());
            return Result.success(pageResult);
        }

        for (OrderVO orderVO : list) {
            Long id = orderVO.getId();
            List<OrderDetail> orderDetailList = orderDetailMapper.list(id);
            orderVO.setOrderDetailList(orderDetailList);
        }

        PageInfo<OrderVO> orderVOPageInfo = new PageInfo<>(list);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(orderVOPageInfo.getTotal());
        pageResult.setRecords(orderVOPageInfo.getList());
        return Result.success(pageResult);
    }

    /**
     * 用户取消订单
     * @param id
     * @return
     */
    @Override
    public Result userCancel(Long id) {
        //只有未付款、商家未接单（还需要退款）的时候才可以取消订单
        Orders orders = orderMapper.getById(id);
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if(orders.getStatus()>2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders1 = new Orders();
        orders1.setId(id);
        if(orders.getStatus()==2){
            //为已支付的进行退款,调用微信接口
            log.info("申请退款:{}",orders.getAmount());

            orders1.setPayStatus(Orders.REFUND);
        }
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason("用户取消");
        orders1.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders1);


        return Result.success();
    }

    /**
     * 再来一单
     * @param id
     * @return
     */
    @Override
    public Result repetition(Long id) {
        //查询出order_detail关联的菜品、套餐信息
        List<OrderDetail> orderDetailList = orderDetailMapper.list(id);
        Long userId = BaseContext.getCurrentId();
        //将信息拷贝至菜品信息，并且添加至集合，后续插入购物车
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(x, shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        shopCartMapper.insertBatch(shoppingCartList);
        return Result.success();
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}
